package com.wsd.smartcarwasher.controller;

import com.alibaba.fastjson.JSONArray;
import com.wsd.smartcarwasher.annotation.Log;
import com.wsd.smartcarwasher.configuration.GetSessionConfig;
import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.PageInfo;
import com.wsd.smartcarwasher.util.ReturnUtil;
import com.wsd.smartcarwasher.util.StringUtil;
import com.wsd.smartcarwasher.util.toExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Api(tags = "优惠券相关接口")
@Controller
@CrossOrigin
public class CouponController {
    private static final Logger logger = LoggerFactory.getLogger(CouponController.class);

    @Resource
    private CouponService couponService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private WxService wxService;
    @Resource
    private PartnerService partnerService;
    @Resource
    private StoreService storeService;
    @Resource
    private MachineService machineService;
    @Log("新增优惠券")
    @RequiresPermissions("coupons:add:new")
    @ApiOperation(value="新增优惠券", notes = "管理端-优惠券管理", produces = "application/json", response = ModelMap.class)
    //@ApiImplicitParam(name = "coupon", value = "优惠券信息", required = true, dataType = "Coupon")
    @RequestMapping(value = "/v1/add_coupon", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap addCoupon(@RequestBody @ApiParam Coupon coupon) {
//        if(!(request.getSession().getAttribute("ispartnerId") ==null))
//        {
//            coupon.setPartnerId(request.getSession().getAttribute("ispartnerId").toString());
//        }
        if (StringUtils.isBlank(coupon.getCouponName())) {
            return ReturnUtil.Error(ResultState.COUPON_NAME_IS_EMPTY.getMsg());
        }
        if (coupon.getType() != Global.COUPON_TYPE_FIX_PRICE && coupon.getType() != Global.COUPON_TYPE_RATE) {
            return ReturnUtil.Error(ResultState.COUPON_TYPE_IS_WRONG.getMsg());
        }
        if(coupon.getType() ==1 && (coupon.getFullPrice() ==null || coupon.getCouponPrice() ==null)){
            return ReturnUtil.Error("请设置合理的价格范围");
        }
        if(coupon.getType() ==2 && coupon.getCouponRate()==null){
            return ReturnUtil.Error("请设置合理的折扣");
        }
        coupon.setStatus(Global.COUPON_STATUS_NORMAL);
        int changeRows = couponService.addCoupon(coupon);
        if (changeRows == 0) {
            return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.ADD_COUPON_SUCCESS.getMsg(), coupon);
    }
    @ApiOperation(value="删除优惠券", notes = "管理端-优惠券管理", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "Integer")
    @RequestMapping(value = "/v1/delete_coupon", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap deleteCoupon(@RequestParam("couponId") int couponId) {
        Coupon coupon = couponService.getCouponByCouponId(couponId);
        if (coupon == null || coupon.getStatus() == Global.COUPON_STATUS_DELETED) {
            return ReturnUtil.Error(ResultState.COUPON_NOT_EXIST.getMsg());
        }
        int changeRows = couponService.deleteCoupon(couponId);
        if (changeRows == 0) {
            return ReturnUtil.Error(ResultState.DELETE_COUPON_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.DELETE_COUPON_SUCCESS.getMsg());
    }

    @ApiOperation(value="商家H5端-删除优惠券", notes = "商家端-优惠券管理", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "Integer")
    @RequestMapping(value = "/v1/partner/delete_coupon", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap storeDeleteCoupon(@RequestParam("couponId") int couponId) {
String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner == null) {
                return ReturnUtil.Error(ResultState.NO_BIND_PARTNER.getMsg());
            } else {
                if(partner.getIs_dataer()==1)
                {
                    return ReturnUtil.Error("权限不足");
                }
                Coupon coupon = this.couponService.getCouponByCouponId(couponId);

                int changeRows = couponService.deleteCoupon(couponId);
                if (changeRows == 0) {
                    return ReturnUtil.Error(ResultState.DELETE_COUPON_FAIL.getMsg());
                }
                return ReturnUtil.Success(ResultState.DELETE_COUPON_SUCCESS.getMsg());

            }

        }
    }


    @ApiOperation(value="商家H5端-查询优惠券", notes = "商家端-优惠券管理", produces = "application/json", response = ModelMap.class)
//    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "Integer")
    @RequestMapping(value = "/v1/partner/get_coupon", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap storeGetCoupon(@RequestParam Integer Page,@RequestParam Integer PageSize,HttpServletRequest request) {

String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {

            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner == null) {
                return ReturnUtil.Error(ResultState.NO_BIND_PARTNER.getMsg());
            } else {
                if (partner.getIs_dataer()==1)
                {
                    List<Coupon> couponList=this.couponService.getCouponByPartnerId(partner.getMajor_account());
                    return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(),new Pagination<Coupon>(Page,PageSize,couponList));

                }
                List<Coupon> couponList=this.couponService.getCouponByPartnerId(partner.getId());
                return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(),new Pagination<Coupon>(Page,PageSize,couponList));
            }
        }
    }
    @ApiOperation(value="商家H5端-查询门店", notes = "商家端-查询门店", produces = "application/json", response = ModelMap.class)
//    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "Integer")
    @RequestMapping(value = "/v1/partner/get_store", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap storeGetStore(HttpServletRequest request) {
String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner == null) {
                return ReturnUtil.Error(ResultState.NO_BIND_PARTNER.getMsg());
            } else {
                if(partner.getIs_dataer()==1)
                {
                    List<Store> storeList=this.storeService.getPartnerList(partner.getMajor_account());
                    return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(),storeList);
                }
                List<Store> storeList=this.storeService.getPartnerList(partner.getId());
                return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(),storeList);
            }
        }

    }

    @ApiOperation(value="商家H5端-根据门店查询底下的机器", notes = "商家端-查询门店底下的机器", produces = "application/json", response = ModelMap.class)
//    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "Integer")
    @RequestMapping(value = "/v1/partner/get_machine", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap storeGetMachine(HttpServletRequest request,HttpServletResponse response) {
        String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner == null) {
                return ReturnUtil.Error(ResultState.NO_BIND_PARTNER.getMsg());
            } else {
                if(partner.getIs_dataer()==1)
                {
                    List<Machine> machineList=this.partnerService.getMachines(partner.getMajor_account());

                    return ReturnUtil.Success("机器查询成功",machineList);
                }
                List<Machine> machineList=this.partnerService.getMachines(partner.getId());

                return ReturnUtil.Success("机器查询成功",machineList);
            }
        }
    }


    @ApiOperation(value="PC端-根据门店查询底下的机器", notes = "PC端-查询门店底下的机器", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/get_machine", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap GetMachine(HttpServletRequest request,@RequestBody StoreIds storeIds) {
                List<Object> machineList=this.machineService.queryStoreMachine(storeIds.getStoreId(),0);
                return ReturnUtil.Success("门店查询成功",machineList);

    }


    @ApiOperation(value="PC端-根据加盟商Id查询底下门店", notes = "PC端-根据加盟商id查询底下的门店", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/get_store", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap GetStore(HttpServletRequest request,@RequestParam(value = "partnerId") int partnerId) {
        List<Store> storeList=this.machineService.queryStore(partnerId);
        return ReturnUtil.Success("门店查询成功",storeList);

    }


//    @Log("商家新增了优惠券")
    @ApiOperation(value="商家H5端--新增优惠券", notes = "商家H5端-优惠券管理", produces = "application/json", response = ModelMap.class)
    //@ApiImplicitParam(name = "coupon", value = "优惠券信息", required = true, dataType = "Coupon")
    @RequestMapping(value = "/v1/partner/add_coupon", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap addPartnerCoupon(@RequestBody  Coupon coupon) {
String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner == null) {
                return ReturnUtil.Error(ResultState.NO_BIND_PARTNER.getMsg());
            } else {
                if(partner.getIs_dataer()==1)
                {
                    return ReturnUtil.Error("权限不足");
                }
                coupon.setPartnerId(partner.getId().toString());
                if (StringUtils.isBlank(coupon.getCouponName())) {
                    return ReturnUtil.Error(ResultState.COUPON_NAME_IS_EMPTY.getMsg());
                }
                if (coupon.getType() != Global.COUPON_TYPE_FIX_PRICE && coupon.getType() != Global.COUPON_TYPE_RATE) {
                    return ReturnUtil.Error(ResultState.COUPON_TYPE_IS_WRONG.getMsg());
                }
                if (coupon.getType() == 1 && (coupon.getFullPrice() == null || coupon.getCouponPrice() == null)) {
                    return ReturnUtil.Error("请设置合理的价格范围");
                }
                if (coupon.getType() == 2 && coupon.getCouponRate() == null) {
                    return ReturnUtil.Error("请设置合理的折扣");
                }
                if(!StringUtil.isNullOrEmpty(coupon.getStartTime())&&!StringUtil.isNullOrEmpty(coupon.getEndTime()))
                {
                    if(coupon.getEndTime().before(coupon.getStartTime()))
                    {
                        return ReturnUtil.Error("优惠券时间设置有误");
                    }
                }
                coupon.setStatus(Global.COUPON_STATUS_NORMAL);
                if(coupon.getStoreId()!=null&&coupon.getStoreId().length()>1){
                    coupon.setStoreId(coupon.getStoreId().substring(0, coupon.getStoreId().length() -1));
                }


                if(coupon.getAvailableMachines()!=null&&coupon.getAvailableMachines().length()>1){
                    coupon.setAvailableMachines(coupon.getAvailableMachines().substring(0, coupon.getAvailableMachines().length() -1));
                }
                int changeRows = couponService.addCoupon(coupon);
                if (changeRows == 0) {
                    return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
                }
                return ReturnUtil.Success(ResultState.ADD_COUPON_SUCCESS.getMsg(), coupon);
            }
            }
        }








    /**
     * 查询所有优惠券信息
     *
     * @return 优惠券信息
     */
    @ApiOperation(value="查询所有优惠券", notes = "管理端-优惠券管理", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/all_coupons", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap getAllCoupons(@RequestParam Integer Page,@RequestParam Integer PageSize) {

        return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(),new PageInfo<>(couponService.queryAllCoupons(Page,PageSize)));
    }

    @ApiOperation(value="商家端--查询所有优惠券", notes = "商家端-优惠券管理", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/store/all_coupons", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap getStoreCoupons(@RequestParam Integer Page,@RequestParam Integer PageSize) {
        GetSessionConfig config=new GetSessionConfig();
        Map<String,String> map= config.getStorePartnerId("查询优惠券",request);
        int partnerId=Integer.parseInt(map.get("partnerId"));
        return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(),new Pagination<>(Page,PageSize,couponService.queryStoreCoupons(partnerId)) );
    }

    /**
     * 查询单个优惠券信息
     *
     * @param couponId 优惠券id
     * @return 优惠券信息
     */
    @ApiOperation(value="查询单个优惠券", notes = "管理端-优惠券管理", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "Integer")
    @RequestMapping(value = "/v1/get_coupon", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap getAllCoupons(@RequestParam("couponId") int couponId) {
        Coupon coupon = couponService.getCouponByCouponId(couponId);

        if (coupon == null) {
            return ReturnUtil.Error(ResultState.COUPON_NOT_EXIST.getMsg());
        }

        return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(), this.couponService.getCouponOneByPartnerId(coupon));
    }

    /**
     * 查询单个优惠券信息
     * @param couponCode
     * @return
     */
    @ApiOperation(value="根据优惠卷码查询", notes = "小程序-优惠券管理", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "String")
    @RequestMapping(value = "/v1/getCouponsByCode", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap getCouponsByCode(@RequestParam("couponCode") String couponCode) {
        Coupon coupon = couponService.getCouponsByCode(couponCode);
        if (coupon == null) {
            return ReturnUtil.Error(ResultState.COUPON_NOT_EXIST.getMsg());
        }
        return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(), coupon);
    }



    /**
     * 查询单个优惠券信息
     *
     * @param couponId 优惠券id
     * @return 优惠券信息
     */
    @Log("生成优惠卷")
    @RequiresPermissions("coupon:add:createUserCoupon")
    @ApiOperation(value="pc端-生成优惠卷", notes = "pc端-生成优惠卷", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "String")
    @RequestMapping(value = "/v1/coupon/createUserCoupon", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap createUserCoupon(@RequestParam("couponId") int couponId) {
        return couponService.createUserCoupon(couponId);//ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(), coupon);
    }

    @ApiOperation(value="商家端-生成优惠卷", notes = "商家端-生成优惠卷", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "String")
    @RequestMapping(value = "/v1/store/coupon/createUserCoupon", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap storeCreateUserCoupon(@RequestParam("couponId") int couponId) {

//        GetSessionConfig config=new GetSessionConfig();
//        Map<String,String> map= config.getStorePartnerId("生成优惠卷",request);
        return couponService.createUserCoupon(couponId);//ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(), coupon);
    }


    /**
     * 查询单个优惠券信息
     *
     * @param couponId 优惠券id
     * @return 优惠券信息
     */
    @Log("优惠卷列表")
    @RequiresPermissions("coupon:get:couponList")
    @ApiOperation(value="pc端-优惠卷列表", notes = "pc端-优惠卷列表", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "String")
    @RequestMapping(value = "/v1/coupon/couponList", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap getCouponListById(@RequestParam("couponId") int couponId,
                                      @RequestParam("Page") int Page,@RequestParam("PageSize")int PageSize
                                      ) {
        return couponService.getCouponListById(couponId,Page,PageSize);//ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(), coupon);
    }

    @Resource
    AdminService adminService;
    /**
     * 导出数据到excel
     * @return
     */
    @Log("导出用户优惠卷")
    @ApiOperation(value="导出用户优惠卷", notes = "导出用户优惠卷", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/coupon/exportExcel", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public void exportExcel(@RequestParam("couponId") int couponId,
                            @RequestParam("id") int id,
                            @RequestParam("password") String password,

                            HttpServletRequest request, HttpServletResponse response) {
        try {
            //Subject subject = SecurityUtils.getSubject();
            Admin admin = adminService.getAdminById(id);
            //String passwordMd5 = (new SimpleHash("MD5", password, admin.getSalt(), 2)).toString();
            if(!password.equals(admin.getPassword())){
                response.reset();
                response.setContentType("application/x-xls");
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Content-Disposition", "attachment;filename=result.xls");

                try {
                    ServletOutputStream out = response.getOutputStream();
                    out.write("".getBytes());
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }


            List<UserCoupon> list = couponService.getCouponListById(couponId);
            String[] title = {"卷码"};
            String[] feild = {"couponCode"};
            new toExcel( JSONArray.toJSONString(list),title,feild,response).createExcel();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            logger.info("exportExcel接口异常", e);

        }
    }


}
